<template>
  <div class="auth-container">
    <div class="auth-card">
      <div class="auth-header">
        <h2>智慧农场管理系统</h2>
        <p>基于W601物联网平台</p>
      </div>

      <div class="auth-tabs">
        <div class="auth-tab active">登录</div>
        <div class="auth-tab" @click="$router.push('/register')">注册</div>
      </div>

      <div v-if="errorMessage" class="alert alert-error">{{ errorMessage }}</div>
      <div v-if="successMessage" class="alert alert-success">{{ successMessage }}</div>

      <form @submit.prevent="handleLogin">
        <div class="form-group">
          <label for="phone">手机号</label>
          <input
              type="text"
              id="phone"
              class="form-control"
              v-model="loginForm.phone"
              placeholder="请输入手机号"
              :disabled="loading"
              required
              @input="clearError"
          >
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <input
              type="password"
              id="password"
              class="form-control"
              v-model="loginForm.password"
              placeholder="请输入密码"
              :disabled="loading"
              required
              @input="clearError"
          >
        </div>

        <button
            type="submit"
            class="btn"
            :disabled="loading"
            :class="{ 'btn-loading': loading }"
        >
          {{ loading ? '登录中...' : '登录' }}
        </button>
      </form>

      <div style="margin-top: 15px; text-align: center; font-size: 14px; color: #718096;">
        测试账号: 18931330889 / 123456
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { useAuthStore } from '@/stores/auth'

export default {
  name: 'Login',
  setup() {
    const authStore = useAuthStore()
    const router = useRouter()

    const loginForm = ref({
      phone: '',
      password: ''
    })

    const errorMessage = ref('')
    const successMessage = ref('')
    const loading = ref(false)

    const handleLogin = async () => {
      // 基础验证
      if (!loginForm.value.phone || !loginForm.value.password) {
        errorMessage.value = '请输入手机号和密码'
        return
      }



      loading.value = true
      errorMessage.value = ''

      try {
        console.log('🔐 1. 开始登录请求...', {
          phone: loginForm.value.phone,
          password: loginForm.value.password.substring(0, 2) + '***'
        })

        // 关键修改：直接传递 phone 和 password
        const result = await authStore.login(loginForm.value.phone, loginForm.value.password)

        console.log('🔐 2. 登录API返回结果:', JSON.stringify(result, null, 2))

        if (result.success) {
          successMessage.value = '登录成功！'

          // 详细检查所有可能的状态
          console.log('🔐 3. 登录成功，详细状态检查:')
          console.log('   - authStore.user:', authStore.user)
          console.log('   - authStore.isLoggedIn():', authStore.isLoggedIn())
          console.log('   - localStorage user:', localStorage.getItem('user'))

          // 检查会话Cookie
          const hasSession = document.cookie.includes('JSESSIONID')
          console.log('   - 会话Cookie存在:', hasSession)
          if (hasSession) {
            const match = document.cookie.match(/JSESSIONID=([^;]+)/)
            if (match) {
              console.log('   - JSESSIONID:', match[1].substring(0, 10) + '...')
            }
          }

          // 延迟跳转确保状态已更新
          setTimeout(() => {
            console.log('🔐 4. 执行跳转...')
            const redirectPath = router.currentRoute.value.query.redirect || '/dashboard/smart-home'
            console.log('   - 跳转目标:', redirectPath)

            router.push(redirectPath).then(() => {
              console.log('✅ 5. 跳转成功!')
            }).catch(error => {
              console.error('❌ 5. 跳转失败:', error)
              // 如果跳转失败，尝试强制跳转
              window.location.href = redirectPath
            })
          }, 100)

        } else {
          errorMessage.value = result.message || '登录失败，请检查手机号和密码'
          console.log('❌ 登录失败:', result.message)
        }
      } catch (error) {
        console.error('💥 登录过程发生错误:', error)
        errorMessage.value = '登录失败，请检查网络连接或联系管理员'

        // 显示更详细的错误信息
        if (error.response) {
          console.error('错误响应:', error.response)
          errorMessage.value = `服务器错误: ${error.response.status} - ${error.response.data?.message || '请稍后重试'}`
        }
      } finally {
        loading.value = false
      }
    }

    // 清除错误信息
    const clearError = () => {
      if (errorMessage.value) {
        errorMessage.value = ''
      }
      if (successMessage.value) {
        successMessage.value = ''
      }
    }

    return {
      loginForm,
      errorMessage,
      successMessage,
      loading,
      handleLogin,
      clearError
    }
  }
}
</script>

<style scoped>
.auth-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 100vh;
  background: linear-gradient(135deg, #2d5a27 0%, #48bb78 100%);
  padding: 20px;
}

.auth-card {
  background-color: white;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.1);
  width: 100%;
  max-width: 400px;
  padding: 30px;
}

.auth-header {
  text-align: center;
  margin-bottom: 25px;
}

.auth-header h2 {
  color: #2d5a27;
  margin-bottom: 10px;
  font-size: 1.5rem;
}

.auth-header p {
  color: #718096;
  font-size: 0.9rem;
}

.auth-tabs {
  display: flex;
  margin-bottom: 20px;
  border-bottom: 1px solid #e2e8f0;
}

.auth-tab {
  flex: 1;
  text-align: center;
  padding: 12px;
  cursor: pointer;
  transition: all 0.3s;
  color: #718096;
  font-weight: 500;
}

.auth-tab.active {
  border-bottom: 3px solid #48bb78;
  color: #2d5a27;
  font-weight: 600;
}

.auth-tab:not(.active):hover {
  color: #4a5568;
  background-color: #f7fafc;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #4a5568;
}

.form-control {
  width: 100%;
  padding: 12px 15px;
  border: 1px solid #cbd5e0;
  border-radius: 5px;
  font-size: 16px;
  transition: all 0.3s;
  box-sizing: border-box;
}

.form-control:focus {
  border-color: #48bb78;
  outline: none;
  box-shadow: 0 0 0 3px rgba(72, 187, 120, 0.1);
}

.form-control:disabled {
  background-color: #f7fafc;
  cursor: not-allowed;
  opacity: 0.7;
}

.btn {
  width: 100%;
  padding: 12px;
  background: linear-gradient(135deg, #48bb78, #2d5a27);
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s;
  position: relative;
}

.btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(72, 187, 120, 0.4);
}

.btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
  transform: none;
}

.btn-loading {
  color: transparent;
}

.btn-loading::after {
  content: '';
  position: absolute;
  width: 20px;
  height: 20px;
  top: 50%;
  left: 50%;
  margin-left: -10px;
  margin-top: -10px;
  border: 2px solid #ffffff;
  border-radius: 50%;
  border-top-color: transparent;
  animation: spin 1s ease-in-out infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.alert {
  padding: 12px;
  border-radius: 5px;
  margin-bottom: 20px;
  text-align: center;
  font-size: 14px;
}

.alert-error {
  background-color: #fed7d7;
  color: #c53030;
  border: 1px solid #feb2b2;
}

.alert-success {
  background-color: #c6f6d5;
  color: #276749;
  border: 1px solid #9ae6b4;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .auth-container {
    padding: 15px;
  }

  .auth-card {
    padding: 20px;
  }

  .auth-header h2 {
    font-size: 1.3rem;
  }
}
</style>